package com.sp2.dev.filter;

import com.sp2.dev.bean.system.CostTime;
import com.sp2.dev.bean.system.CostTimeThread;
import com.sp2.dev.constant.MessageProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 * User: zhimingli
 * Date: 14-1-24
 * Time: 上午11:57
 * To change this template use File | Settings | File Templates.
 */
public class CostTimeInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(CostTimeInterceptor.class);

    private NamedThreadLocal<Long> startTimeThre = new NamedThreadLocal<Long>("stopWatch-startTime");

    //预处理回调
    //true 继续流程
    //false 流程中断 需要response返回响应
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("TestInterceptor preHandle");
        //开始时间
        long beginTime = System.currentTimeMillis();
        //线程绑定变量(该数据只有当前请求的线程可见)
        startTimeThre.set(beginTime);
        return true;
    }

    //后处理回调方法
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("TestInterceptor postHandle");
    }

    /**
     * 整个请求处理完毕回调方法，即在视图
     *
     * @param request
     * @param response
     * @param o
     * @param e
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

        //开始时间
        long endTime = System.currentTimeMillis();
        long beginTime = startTimeThre.get();
        long time = endTime - beginTime;
        String requestUrl = request.getRequestURI();
        logger.info(requestUrl + "----------function cost timessswwwwwwwww-------------" + time);


        //记录每个方法花费的时间
        if ("true".equalsIgnoreCase(MessageProperties.save_cost_time)) {
            String method = request.getMethod();
            CostTime costTime = new CostTime();
            costTime.setUrl(requestUrl);
            costTime.setCosttime(time);
            costTime.setRequestmethod(method.toLowerCase());
            CostTimeThread costTimeThread = new CostTimeThread(costTime);
            costTimeThread.start();
        }
        System.out.println("TestInterceptor afterCompletion");
    }
}
